package com.redwine.app.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.APP;
import com.redwine.app.ApplyForSupplierActivity;
import com.redwine.app.MyOfferActivity;
import com.redwine.app.MyPublishedSourcesActivity;
import com.redwine.app.MySendProcurementActivity;
import com.redwine.app.PersonalInfoActivity;
import com.redwine.app.PurchaserCertificationActivity;
import com.redwine.app.R;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.model.User;
import com.redwine.app.net.responses.LoginResponse;
import com.redwine.app.net.responses.RedwineDetailResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Settings;
import com.redwine.app.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 我的主页
 * 作者：gassion on 17/8/26 18:20
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MeFragment extends BaseFragment {


    @ViewInject(R.id.me_iv_user_photo_all_bg)
    ImageView meIvUserPhotoAllBg;
    @ViewInject(R.id.me_iv_user_photo)
    ImageView meIvUserPhoto;
    @ViewInject(R.id.me_tv_user_name)
    TextView meTvUserName;
    @ViewInject(R.id.me_tv_purchaser_certification)
    TextView meTvPurchaserCertification;
    @ViewInject(R.id.me_tv_supplier_certification)
    TextView meTvSupplierCertification;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    private View rootView;
    private Intent intent;
    private RedwineDetailResponse.DataEntity.PublishEntity publishEntity;
    private boolean isSupplierStatus;
    private boolean isBuyerStatus;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_me, container, false);
            ViewUtils.inject(this, rootView);
            EventBus.getDefault().register(this);
            initView();
        }
        return rootView;
    }

    private void requestData() {
        String url = NetworkConstants.GET_USERINFO_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<LoginResponse> request = new GsonRequest<>(url, Request.Method.POST,
                LoginResponse.class, false, params, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response) {
                if (response.isSuccess()) {
                    //如果登陆直接跳转到主页面
                    try {
                        User responseData = response.getData();
                        Settings.setSharedPreferences(Settings.SUPPLIER_STATUS, responseData.getSupplier_status());
                        Settings.setSharedPreferences(Settings.BUYER_STATUS, responseData.getBuyer_status());
                        isSupplierStatus = Utils.setCertificationStatus(meTvSupplierCertification, responseData.getSupplier_status());
                        isBuyerStatus = Utils.setCertificationStatus(meTvPurchaserCertification, responseData.getBuyer_status());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    private void initView() {
        headerTitle.setText(getString(R.string.personal_center));
        if (null != Global.user) {
            String avatar = Global.user.getAvatar();
            BitmapUtils.loadImage(meIvUserPhotoAllBg, avatar, BitmapUtils.GAOSI);
            BitmapUtils.loadImage(meIvUserPhoto, avatar, BitmapUtils.ROUND);
            meTvUserName.setText(Global.user.getNickname());
        }
    }


    public void onResume() {
        super.onResume();
        initView();
        requestData();
        MobclickAgent.onPageStart("MainScreen");

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @OnClick({R.id.me_ll_purchaser_certification, R.id.me_rl_person_detail, R.id.me_ll_supplier_certification,
            R.id.me_ll_send_supply_of_goods, R.id.me_ll_send_procurement, R.id.me_ll_send_offer})
    public void mClick(View v) {
        switch (v.getId()) {
            //采购商认证
            case R.id.me_ll_purchaser_certification:
                if (isBuyerStatus)
                    return;
                publishEntity = new RedwineDetailResponse.DataEntity.PublishEntity();
                publishEntity.setUid(Global.user.getUid());
                intent = new Intent(getActivity(), PurchaserCertificationActivity.class);
                intent.putExtra(ApplyForSupplierActivity.PUBLISH_ENTITY, publishEntity);
                startActivity(intent);
                break;

            //供应商认证
            case R.id.me_ll_supplier_certification:
                if (isSupplierStatus)
                    return;
                publishEntity = new RedwineDetailResponse.DataEntity.PublishEntity();
                publishEntity.setUid(Global.user.getUid());
                intent = new Intent(getActivity(), ApplyForSupplierActivity.class);
                intent.putExtra(ApplyForSupplierActivity.PUBLISH_ENTITY, publishEntity);
                startActivity(intent);
                break;

            //我发布的货源
            case R.id.me_ll_send_supply_of_goods:
                intent = new Intent(getActivity(), MyPublishedSourcesActivity.class);
                startActivity(intent);
                break;

            //我发布的采购
            case R.id.me_ll_send_procurement:
                intent = new Intent(getActivity(), MySendProcurementActivity.class);
                startActivity(intent);
                break;

            //我发布的报价
            case R.id.me_ll_send_offer:
                intent = new Intent(getActivity(), MyOfferActivity.class);
                startActivity(intent);
                break;

            //个人详情
            case R.id.me_rl_person_detail:
                intent = new Intent(getActivity(), PersonalInfoActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.REFURBISH_PHPTO_DATA) {
            initView();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}